package middleware

import (
	"invitation/internal/config"
	"invitation/internal/pojo/dto"
	"invitation/internal/repository"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

type RequestExtractor struct {
	applicationConfig *config.ApplicationConfig
	repoManager       *repository.RepoManager

	validator *validator.Validate
}

func NewRequestExtractor(repoManager *repository.RepoManager, applicationConfig *config.ApplicationConfig) *RequestExtractor {
	v := validator.New()
	return &RequestExtractor{
		applicationConfig: applicationConfig,
		repoManager:       repoManager,
		validator:         v,
	}
}

const (
	LocalKeysInvitationGenerateRequest = "invitation_generate_request"
	LocalKeysSelectedGames             = "selected_games"
)

func (re *RequestExtractor) ParseUserInput() func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		var generateReq dto.InvitationPayload
		err := ctx.BodyParser(&generateReq)
		if err != nil {
			// 建议使用 400 Bad Request 表示客户端输入错误
			return ctx.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"message": "Invalid request body: " + err.Error(),
			})
		}
		log.Debug().Msgf("generateReq: %v", generateReq)

		err = re.validator.Struct(generateReq)
		if err != nil {
			// 同样，验证失败也应该是 400
			return ctx.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"message": "Validation failed: " + err.Error(),
			})
		}
		ctx.Locals(LocalKeysInvitationGenerateRequest, generateReq.UserInput)

		return ctx.Next()
	}
}
